//
//  BAHomePictureView.swift
//  BAweibo
//
//  Created by baggio on 2017/8/19.
//  Copyright © 2017年 baggio. All rights reserved.
//

import UIKit
import SDWebImage

class BAHomePictureView: UICollectionView {
    //每个图的宽和高（宽==高），距左右两边距各 BA_HOME_CELL_MARGIN
    private let cellWH = (BA_SCREEN_WIDTH - 2 * BA_HOME_CELL_MARGIN - 2 * BA_HOME_PICTURE_MARGIN) / 3
    
    //提供一个属性供外界赋值
    //这不要传递 homeViewModel，因为原创微博的配图需要的是 homeViewModel?.homeModel?.pic_urls，而转发微博的配图需要的是 homeViewModel?.homeModel?.retweeted_status?.pic_urls
    var picUrls: [BAPictureUrlModel]? {
        didSet{
            let size = dealPictureViewSize(picCount: picUrls!.count)
            //更新约束
            self.snp.updateConstraints { (m) in
                m.size.equalTo(size)
            }
            
            //不要忘了赋完值后要刷新
            reloadData()
        }
    }
    
    //根据图片数量计算 pictureView 的尺寸
    private func dealPictureViewSize(picCount: Int) -> CGSize {
        //item 的宽度必须小于 colletionView 的宽度
        //得到flowLayout
        let flowLayout = self.collectionViewLayout as! UICollectionViewFlowLayout
        
        //需求：单张图，用原始尺寸，同时也要限制最小最大宽度和高度
        if picCount == 1 {
            //获取本地图片，key 就是图片的 url
            if let image = SDWebImageManager.shared().imageCache?.imageFromDiskCache(forKey: picUrls?.first?.thumbnail_pic) {
                var picW = image.size.width
                var picH = image.size.height
                
                if picW < 80 {
                    picW = 80
                    //等比例缩放高度
                    picH = image.size.height * picW / image.size.width
                }
                if picW > 200 {
                    picW = 200
                    picH = image.size.height * picW / image.size.width
                }

                //修改 flowLayout
                flowLayout.itemSize = CGSize(width: picW, height: picH)
                
                return CGSize(width: picW, height: picH)
            }
        }
        
        //需求：4张图，2*2布局
        if picCount == 4 {
            let wh: CGFloat = 130
            
            //修改 flowLayout
            flowLayout.itemSize = CGSize(width: wh, height: wh)
            
            return CGSize(width: 2 * wh + BA_HOME_PICTURE_MARGIN, height: 2 * wh+BA_HOME_PICTURE_MARGIN)
        }
        
        //计算行数、列数
        let rowCount = (picCount - 1)/3 + 1 //小算法
        let colCount = (picCount > 3) ? 3 : picCount //超过3个，列就是3
        
        let picViewW = CGFloat(colCount) * cellWH + CGFloat(colCount - 1) * BA_HOME_PICTURE_MARGIN
        let picViewH = CGFloat(rowCount) * cellWH + CGFloat(rowCount - 1) * BA_HOME_PICTURE_MARGIN
        
        //添加了单张图片的逻辑以后，这里也需要修改 flowLayout，因为可能被单张图片的时候改过了
        flowLayout.itemSize = CGSize(width: cellWH, height: cellWH)
        
        return CGSize(width: picViewW, height: picViewH)
    }
    
    
    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        // UICollectionView 初始化需要一个 Layout
        let flowLayout = UICollectionViewFlowLayout()
        
        //默认 cell 的大小和间距都不符合需求
        //cell 间距（默认 minimumLineSpacing 是10，minimumInteritemSpacing 是一点点）
        flowLayout.minimumInteritemSpacing = BA_HOME_PICTURE_MARGIN
        flowLayout.minimumLineSpacing = BA_HOME_PICTURE_MARGIN
        //cell 大小
        flowLayout.itemSize = CGSize(width: cellWH, height: cellWH)
        
        super.init(frame: frame, collectionViewLayout: flowLayout)
  
        
        setUpUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setUpUI() {
        backgroundColor = randomColor()
        
        //UICollectionViewController 默认实现了 UICollectionViewDelegate 和 UICollectionViewDataSource，所以不用设置 dataSource 和 delegate了，但是 UICollectionView 并没有
        dataSource = self
        
        //注册 cell，先使用系统 cell
//        register(UICollectionViewCell.self, forCellWithReuseIdentifier: "cell")
        //使用自定义的 cell
        register(BAHomePictureViewCell.self, forCellWithReuseIdentifier: "cell")
        
        

    }
}

// dataSource
extension BAHomePictureView: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return picUrls?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        //先使用系统 cell
//        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath)
//        cell.backgroundColor = randomColor()
        //使用自定义的 cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! BAHomePictureViewCell
        
        cell.picUrl = picUrls?[indexPath.row]
        
        return cell
    }
}
